import React from 'react'
import propTypes from 'prop-types'
import { filterProperties } from '../../utils'
import { getPosition, getLineNumber } from './selection'
import './leditor.css'

const textAreaPropsFilter = [
  'rows',
  'cols',
  'autocomplete',
  'autofocus',
  'disabled',
  'placeholder',
  'readOnly',
  'required',
  'maxlength',
  'minlength',
  'wrap',
]

export default class Leditor extends React.Component {

  static propTypes = {
    // src: propTypes.string.isRequired
    resize: propTypes.string
  }

  static defaultProps = {
    resize: "none"
  }

  state = {
    content: '',
    lineNum: 0
  }

  textareaProps = () => {
    const props = this.props
    return filterProperties(props, textAreaPropsFilter, true)
  }

  handleOnInput = (event) => {
    const lineNum = getLineNumber(event.target.value)
    this.setState({
      content: event.target.value,
      lineNum: lineNum
    })
  }

  componentDidMount() {

  }

  textareaClassName = () => {
    let className = 'l-editor-l-textarea'
    if (this.props.resize === 'none') {
      className += ' l-textarea-no--resize'
    }
    if (this.props.className) {
      className += ` ${this.props.className}`
    }
    return className
  }

  handleOnkeydown = (event) => {
    const { key, code, target } = event
    if (key === 'Tab' || code === 'Tab') {
      event.preventDefault()
      let pointer = getPosition(target)
      const { value } = target
      const insertValue = `${value.slice(0, pointer)}\t${value.slice(pointer)}`
      target.value = insertValue
      this.setState({
        content: insertValue
      })
    }
  }

  render() {

    return (
      <div className='l-editor'>
        <div className='l-editor--toptool'>

        </div>
        <div className='l-editor__content'>
          <div className='l-editor-line-number'>
            
          </div>
          <textarea
            {...this.textareaProps()}
            className={this.textareaClassName()}
            onInput={this.handleOnInput}
            onKeyDown={this.handleOnkeydown}
          >
          </textarea>
        </div>
      </div>

    )
  }
}